package com.vegetable.modules.controller.stock;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vegetable.common.annotation.SysLog;
import com.vegetable.common.utils.R;
import com.vegetable.modules.controller.AbstractController;
import com.vegetable.modules.entity.stock.PriceAlert;
import com.vegetable.modules.service.stock.IPriceAlertService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * <p>
 * 价格预警设置表 前端控制器
 * </p>
 *
 * @author qoder
 * @since 2025-09-11
 */
@Slf4j
@RestController
@RequestMapping("/priceAlert")
@AllArgsConstructor
@Api(tags = "价格预警设置")
public class PriceAlertController extends AbstractController {

    private final IPriceAlertService priceAlertService;

    @SysLog(value = "查看价格预警设置列表")
    @GetMapping("/list")
    @ApiOperation(value = "获取价格预警设置列表", notes = "分页获取价格预警设置列表")
//    @RequiresPermissions("stock:price:alert:list")
    public R<Page<PriceAlert>> list(
            @ApiParam(value = "商品名称(模糊查询)") @RequestParam(value = "commodityNameLike", required = false) String commodityNameLike,
            @ApiParam(value = "页码", example = "1") @RequestParam(value = "page", defaultValue = "1") Long page,
            @ApiParam(value = "每页数量", example = "10") @RequestParam(value = "size", defaultValue = "10") Long size) {
        
        log.info("用户{}请求价格预警设置列表，商品名称：{}，页码：{}，每页数量：{}", getUserId(), commodityNameLike, page, size);
        
        try {
            Page<PriceAlert> pageParam = new Page<>(page, size);
            QueryWrapper<PriceAlert> queryWrapper = new QueryWrapper<>();
            
            if (commodityNameLike != null && !commodityNameLike.isEmpty()) {
                queryWrapper.like("commodity_name", commodityNameLike);
            }
            
            queryWrapper.orderByDesc("create_time");
            Page<PriceAlert> result = priceAlertService.page(pageParam, queryWrapper);
            return R.data(result);
        } catch (Exception e) {
            log.error("获取价格预警设置列表失败", e);
            return R.fail("获取价格预警设置列表失败：" + e.getMessage());
        }
    }

    @SysLog(value = "查看价格预警设置详情")
    @GetMapping("/info/{id}")
    @ApiOperation(value = "获取价格预警设置详情", notes = "根据ID获取价格预警设置详情")
//    @RequiresPermissions("stock:price:alert:info")
    public R<PriceAlert> info(@ApiParam(value = "价格预警设置ID", required = true) @PathVariable("id") Long id) {
        
        log.info("用户{}请求价格预警设置详情，ID：{}", getUserId(), id);
        
        try {
            PriceAlert priceAlert = priceAlertService.getById(id);
            if (priceAlert == null) {
                return R.fail("未找到对应的价格预警设置");
            }
            return R.data(priceAlert);
        } catch (Exception e) {
            log.error("获取价格预警设置详情失败", e);
            return R.fail("获取价格预警设置详情失败：" + e.getMessage());
        }
    }

    @SysLog(value = "保存价格预警设置")
    @PostMapping("/save")
    @ApiOperation(value = "保存价格预警设置", notes = "保存价格预警设置信息")
//    @RequiresPermissions("stock:price:alert:save")
    public R<String> save(@RequestBody PriceAlert priceAlert) {
        
        log.info("用户{}保存价格预警设置，商品ID：{}，阈值：{}", getUserId(), priceAlert.getCommodityId(), priceAlert.getPriceThreshold());
        
        try {
            // 设置创建者ID
            priceAlert.setCreateUserId(getUserId());
            priceAlert.setCreateTime(new Date());
            priceAlert.setUpdateTime(new Date());
            
            // 检查是否已存在相同商品的价格预警设置
            QueryWrapper<PriceAlert> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("commodity_id", priceAlert.getCommodityId());
            if (priceAlertService.getOne(queryWrapper) != null) {
                return R.fail("该商品已存在价格预警设置");
            }
            
            boolean result = priceAlertService.save(priceAlert);
            if (result) {
                return R.success("保存成功");
            } else {
                return R.fail("保存失败");
            }
        } catch (Exception e) {
            log.error("保存价格预警设置失败", e);
            return R.fail("保存价格预警设置失败：" + e.getMessage());
        }
    }

    @SysLog(value = "修改价格预警设置")
    @PostMapping("/update")
    @ApiOperation(value = "修改价格预警设置", notes = "修改价格预警设置信息")
//    @RequiresPermissions("stock:price:alert:update")
    public R<String> update(@RequestBody PriceAlert priceAlert) {
        
        log.info("用户{}修改价格预警设置，ID：{}，阈值：{}", getUserId(), priceAlert.getId(), priceAlert.getPriceThreshold());
        
        try {
            priceAlert.setUpdateTime(new Date());
            
            boolean result = priceAlertService.updateById(priceAlert);
            if (result) {
                return R.success("修改成功");
            } else {
                return R.fail("修改失败");
            }
        } catch (Exception e) {
            log.error("修改价格预警设置失败", e);
            return R.fail("修改价格预警设置失败：" + e.getMessage());
        }
    }

    @SysLog(value = "删除价格预警设置")
    @PostMapping("/delete/{id}")
    @ApiOperation(value = "删除价格预警设置", notes = "根据ID删除价格预警设置")
//    @RequiresPermissions("stock:price:alert:delete")
    public R<String> delete(@ApiParam(value = "价格预警设置ID", required = true) @PathVariable("id") Long id) {
        
        log.info("用户{}删除价格预警设置，ID：{}", getUserId(), id);
        
        try {
            boolean result = priceAlertService.removeById(id);
            if (result) {
                return R.success("删除成功");
            } else {
                return R.fail("删除失败");
            }
        } catch (Exception e) {
            log.error("删除价格预警设置失败", e);
            return R.fail("删除价格预警设置失败：" + e.getMessage());
        }
    }

}